package org.example.common.handler;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.example.pinda.base.CommonResult;
import org.springframework.http.HttpRequest;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;

import static org.example.pinda.exception.code.ExceptionCode.PARAM_EX;

/**
 * 默认全局异常处理器
 *
 * @author ryan fawcett
 */
@Slf4j
public abstract class DefaultGlobalExceptionHandler {

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public CommonResult<String> httpMessageNotReadableExceptionHandler(HttpMessageNotReadableException ex, HttpRequest request) {
        log.warn("HttpMessageNotReadableException:", ex);
        String message = ex.getMessage();
        if (StrUtil.containsAny(message, "Could not read document:")) {
            String msg = String.format("无法正确的解析json类型的参数：%s", StrUtil.subBetween(message,
                    "Could not read document:", " at "));
            return CommonResult.result(PARAM_EX.getValue(), StrUtil.EMPTY, msg);
        }
        return CommonResult.result(PARAM_EX.getValue(), StrUtil.EMPTY,
                PARAM_EX.getText());
    }

}
